<?php
namespace app\api\controller\com;
use app\api\base\RestfulBase;
use think\Config;
use Wechat\TPWechat;

class Wechat extends RestfulBase
{
    protected $_open_auth = ['user' => false, 'open_api' => false];
    protected $wechatObj;

    public function _initialize()
    {
        $options = Config::get('wechat');
        $this->wechatObj = new TPWechat($options);
    }

    public function index(){
        if ($this->request->isGet()){
            $code = $this->getParams('code','','trim,strip_tags');

            if ($code){
//                echo $this->get_url();exit();
                return $this->apiSuccess($this->get_url());
//                return $this->apiSuccess($code);
            }else{
                return $this->apiSuccess($this->get_oauth(1));
            }
        }else{
           return $this->apiError('无效请求');
        }

}

    public function wx_config(){
        $config['appid'] = Config::get('wechat.appid');
        if ($config && is_array($config)){
            return $this->apiSuccess($config);
        }else{
            return $this->apiError('配置获取失败！');
        }

    }

    //获取授权--0:基本信息授权,1:所有信息授权
    protected function get_oauth($all=0)
    {
        $url=$this->get_url();
        $type=$all==1?'snsapi_userinfo':'snsapi_base';
        $wx_url=$this->wechatObj->getOauthRedirect($url,$type,$type);
        return $wx_url;

    }

    //获取当前地址
    public function get_url()
    {
        //协议
        $protocol=isset($_SERVER['SERVER_PORT'])&&$_SERVER['SERVER_PORT']=='443'?'https://':'http://';
        //入口
        $main=$_SERVER['PHP_SELF']?$_SERVER['PHP_SELF']:$_SERVER['SCRIPT_NAME'];
        //参数
        $parm=isset($_SERVER['PATH_INFO'])?$_SERVER['PATH_INFO']:'';
        //地址
        $url=isset($_SERVER['REQUEST_URI'])?$_SERVER['REQUEST_URI']:$main.(isset($_SERVER['QUERY_STRING'])?'?'.$_SERVER['QUERY_STRING']:$parm);
        //返回地址
        return $protocol.(isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:'').$url;
    }
}